<template>
  <ConfigForm ref="formRef" :configs="editForm" rawKey="arrears_data_id" :info="info" :server="litServer"
    :beforeSubmit="beforeSubmit" />
</template>

<script setup lang="jsx">
import { litServer } from '@/api/arrears'
import ConfigForm from '@/components/CRUD/ConfigForm.vue'
import { ref } from 'vue'
import ElMoney from '@/components/ElMoney.vue'

const props = defineProps({
  info: {
    type: Object,
    default: () => ({})
  },
})

const formRef = ref()
const onChangeBackAmount = (val) => {
  formRef.value?.updateForm(() => {
    if (val) {
      return {
        back_amount: props.info.last_amount
      }
    }
  })
}
const onChangeIsAll = (val) => {
  formRef.value?.updateForm(() => {
    return {
      is_all_money_back: val === props.info.last_amount
    }
  })
}

const editForm = [
  {
    label: '',
    key: 'arrears_data_id',
    type: 'custom',
    render: () => (
      <div class="flex w-full gap-4">
        <span>{`${props.info.company_name}/${props.info.community_name}`}</span>
        <span>{props.info.address}</span>
        <span>{props.info.name}</span>
        <span>{props.info.mobile}</span>
        <span>{props.info.case_reason}</span>
      </div>
    )
  },
  {
    label: '是否全额收回',
    key: 'is_all_money_back',
    type: 'radio',
    defaultValue: true,
    options: [
      { label: '是', value: true },
      { label: '否', value: false }
    ],
    props: {
      onChange: onChangeBackAmount
    },
  },
  {
    label: '待收回金额',
    key: 'last_amount',
    type: 'custom',
    render: () => (
      <div class="font-bold">
        <ElMoney num={props.info.last_amount} />（欠费金额<ElMoney num={props.info.amount} /> 滞纳金<ElMoney num={props.info.overdue_fine_amount} /> 减免金额<ElMoney num={props.info.discount_amount} />）
      </div>
    )
  },
  {
    label: '收回金额',
    key: 'back_amount',
    type: 'number',
    required: true,
    defaultValue: props.info.last_amount,
    props: {
      placeholder: '请输入收回金额',
      precision: 2,
      min: 0,
      max: props.info.last_amount,
      onChange: onChangeIsAll
    },
  },
  {
    label: '剩余未缴费周期',
    key: 'last_date',
    type: 'datepicker',
    show: (form) => form.back_amount !== props.info.last_amount,
    required: true,
    props: {
      type: 'daterange',
      startPlaceholder: '请选择开始时间',
      endPlaceholder: '请选择结束时间',
      valueFormat: 'YYYY-MM-DD',
      rangeSeparator: '至',
    },
  },
]

const beforeSubmit = (params) => {
  return {
    arrears_data_id: props.info.arrears_data_id,
    back_amount: params.back_amount,
    is_all_money_back: params.back_amount === props.info.last_amount,
    last_start_datetime: params.last_date ? params.last_date[0] + ' 00:00:00' : null,
    last_end_datetime: params.last_date ? params.last_date[1] + ' 23:59:59' : null,
  }
}
</script>